package com.showcai.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.reflect.TypeToken;
import com.showcai.dao.OrderActivityRelativeMapper;
import com.showcai.dao.OrderItemMapper;
import com.showcai.dao.OrderMapper;
import com.showcai.module.*;
import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.service.*;
import com.showcai.util.DateUtil;
import com.showcai.tools.json.JsonHandler;
import com.showcai.util.GenerateID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by baggio on 2016/12/27.
 */
@Service
public class OrderServiceImpl extends ServiceBase implements OrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    PaymentService paymentService;
    @Autowired
    OrderItemService orderItemService;

    @Autowired
    @Qualifier("weChatPayService")
    private PayService weChatPayService;
    @Autowired
    @Qualifier("aliPayService")
    private PayService aliPayService;
    @Autowired
    @Qualifier("groupPayService")
    private PayService groupPayService;

    @Autowired
    UserService userService;
    @Autowired
    ProductEntityService productEntityService;

    @Autowired
    OrderActivityRelativeMapper orderActivityRelativeMapper;
    /*   @Autowired
      ConsigneeInfoService  consigneeInfoService;
     @Autowired
      BindDistributorMapper bindDistributorMapper;
  */
    @Transactional
    @Override
    public Order createOrder(List<Long> productEntityIdList, Long userId, List<Long> activittyIdList, Byte orderSourceId) {
        if (userId == null) {
            throw new MyRunTimeExcption("userId is null！");
        }

        User user = userService.getUserById(userId);

        if (user == null) {
            throw new MyRunTimeExcption("用户不存在！");
        }

        Long orderId = GenerateID.CreatetID();

        logger.info("【User：“+customerId+”====》createOrder====>OrderId :】" + orderId);
        logger.info("【User： :】" + user.toString());
        Order order = new Order();
        order.setOrderId(orderId);
        order.setStatus(OrderService.UNPAY);
        order.setCreateTime(new Date());


        order.setUserId(user.getTid());

        if (productEntityIdList == null || productEntityIdList.size() == 0) {
            throw new MyRunTimeExcption("没有选择产品！");
        }

        if (orderSourceId != null) {
            order.setOrderSourceId(orderSourceId);
        }

        Integer price = orderItemService.createOrderItem(orderId, productEntityIdList, userId, activittyIdList);


        order.setOrderPrice(price);
        orderMapper.insertOrder(order);
        if(activittyIdList!=null && activittyIdList.size()>0 ){
            for (Long activityId :activittyIdList
                 ) {
                OrderActivityRelative orderActivityRelative=new OrderActivityRelative();
                orderActivityRelative.setOrderId(order.getOrderId());
                orderActivityRelative.setActivityId(activityId);
                orderActivityRelativeMapper.insertOrderActivityRelative(orderActivityRelative);
            }


        }

   /*  ConsigneeInfo consigneeInfo=new ConsigneeInfo();
        consigneeInfo.setCreateTime(new Date());
        consigneeInfo.setConsigneeAddress(user.getUserAddress());
        consigneeInfo.setConsigneeName(user.getUserName());
        consigneeInfo.setConsigneePhone(user.getPhone());
        consigneeInfo.setOrderId(orderId);
        consigneeInfoService.modifyConsigneeInfo(consigneeInfo);*/
        return order;
    }

    @Override
    public Boolean cancelOrder(Long orderId) {
        logger.info("cancelOrder====>" + orderId);
        Order order = orderMapper.getOrderById(orderId);
        if (order == null) {
            throw new MyRunTimeExcption("订单号错误！");
        }

        order.setStatus(OrderService.CANCEL);
        orderMapper.updateOrderById(order);

        List<OrderItem> orderItemList = orderItemService.getOrderItemByOrderId(orderId);
        for (OrderItem orderItem : orderItemList) {
            orderItem.setStatus(OrderService.CANCEL);
            orderItemMapper.updateOrderItemById(orderItem);
        }
        return true;
    }


    @Override
    public Boolean modifyOrder(Order order) {
        orderMapper.updateOrderById(order);
        return true;
    }


    @Transactional
    @Override
    public Byte toPay(Long orderId, String paymentJSON) throws Exception {
        logger.info("【toPay====>orderId :】" + orderId);
        Order order = orderMapper.getOrderById(orderId);
        if (order == null) {
            throw new MyRunTimeExcption("订单没有找到");
        }
        if (order.getStatus() != OrderService.UNPAY) {
            throw new MyRunTimeExcption("订单状态不能完成支付");
        }

        if (DateUtil.hoursBetween(order.getCreateTime(), new Date()) > 24) {

            modifyOrderStatus(orderId, OrderService.OVER_TIME);
            throw new MyRunTimeExcption("订单操时！");

        }

        if (org.apache.commons.lang3.StringUtils.isBlank(paymentJSON)) {
            throw new MyRunTimeExcption("沒有支付方式！");
        }

        List<OrderItem> orderItemList = orderItemService.getOrderItemByOrderId(orderId);
        if (orderItemList == null || orderItemList.size() == 0) {
            throw new MyRunTimeExcption("订单项目没有找到");
        }

        List<Payment> paymentList = JsonHandler.json2ObjList(paymentJSON, new TypeToken<List<Payment>>() {
        });
        Integer payPrice = 0;
        for (Payment payment : paymentList
                ) {
            payment.setCreateTime(new Date());
            paymentService.insertPayment(payment);
            payPrice += payment.getPrice();
        }

        if (payPrice.intValue() != order.getOrderPrice().intValue()) {
            logger.info(payPrice.intValue() + "<payPrice=======================orderPrice>" + order.getOrderPrice().intValue());
            throw new MyRunTimeExcption("payment价格错误");
        }

        // order.setPaymentList(paymentList);

        orderMapper.updateOrderById(order);
        PayParameter payParameter = null;
        PayService payService = null;
        Byte payMode = null;
        for (Payment payment : paymentList
                ) {
            //三方支付，目前只有WAP微信，以后加再说
            if (payment.getPayMode() == Payment.PAY_MODE_WECHAT_BY_WAP) {
                payMode = payment.getPayMode();
            } else {
                //处理站内支付，积分、卡券、余额等
                getPayService(payment.getPayMode()).pay(orderId, payment.getPrice(), null, null);
                Map<String, String> map = new HashMap<>();
                map.put("orderId", String.valueOf(orderId));
                map.put("payMode", String.valueOf(payment.getPayMode()));
                getPayService(payment.getPayMode()).notification(map);
            }

        }

        return payMode;

    }

    @Override
    public String payParameterStrBypayMode(Byte payMode, Long orderId, Integer price, String remoteAddr, Map<String, String> payParametersMap) throws Exception {
        return getPayService(payMode).getPayParameterStr(orderId, price, remoteAddr, payParametersMap);
    }

    @Override
    public PayParameter getPayParameterBypayMode(Byte payMode, Long orderId, Integer price, String dataString, String ticket) throws Exception {
        return getPayService(payMode).pay(orderId, price, dataString, ticket);
    }


    private PayService getPayService(Byte payMode) {
        System.out.println("payMode==========================>>>>>" + payMode);
/*        if (payMode == Payment.PAY_MODE_WECHAT) {
            return weChatPayService;
        }*/
     if (payMode == Payment.PAY_MODE_WECHAT_BY_WAP) {
            return weChatPayService;
        }
        if (payMode == Payment.PAY_MODE_ALIPAY_BY_WAP) {
            return aliPayService;
        }
        if (payMode == Payment.PAY_MODE_ALIPAY) {
            return aliPayService;
        }
        if (payMode == Payment.PAY_MODE_GROUPPAY_BY_QXPC) {
            return groupPayService;
        }
        return null;

    }

    @Override
    public Order getOrderById(Long orderId) {
        return orderMapper.getOrderById(orderId);
    }

    @Override
    public Order getOrder(Map<String, String> map) {
        return orderMapper.getOrder(map);
    }


    @Override
    public List<Order> getOrderList(Map<String, String> map) {
        return orderMapper.getOrderList(map);
    }

    @Override
    public PageInfo getOrderPageList(Map<String, String> map) {
        Integer page = Integer.parseInt(map.get("page"));
        Integer pageSize = Integer.parseInt(map.get("pageSize"));
        PageHelper.startPage(page, pageSize);
        List<Order> list = orderMapper.getOrderList(map);
        PageInfo<Order> pageinfo = new PageInfo<>(list);
        return pageinfo;
    }

    @Override
    public List<Order> getOrderByUserId(Long userId) {
        return orderMapper.getOrderByUserId(userId);
    }

    @Override
    public Boolean modifyOrderStatus(Long orderId, Byte status) {
        Order order = orderMapper.getOrderById(orderId);
        order.setStatus(status);
        orderMapper.updateOrderById(order);
        return true;
    }


    @Override
    public PageInfo groupPayList(Map<String, String> map) {
        Integer page = Integer.parseInt(map.get("page"));
        Integer pageSize = Integer.parseInt(map.get("pageSize"));
        PageHelper.startPage(page, pageSize);
        List<Order> list = orderMapper.groupPayList(map);
        PageInfo<Order> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public Boolean closeOrder(Long orderId) {
        Order order = orderMapper.getOrderById(orderId);
        if (order == null) {
            throw new MyRunTimeExcption("订单没有找到！");
        }
        order.setStatus(OrderService.CLOSE);
        orderMapper.updateOrderById(order);
        return true;
    }

    @Override
    public Boolean completeOrder(Long orderId) {
        Order order = orderMapper.getOrderById(orderId);
        if (order == null) {
            throw new MyRunTimeExcption("订单没有找到！");
        }
        List<OrderItem> orderItemList = orderItemService.getOrderItemByOrderId(orderId);
        for (OrderItem orderItem : orderItemList
                ) {

            orderItemService.modifyOrderItemStatus(orderItem.getOrderItemId(), OrderService.COMPELTEED);
        }
        order.setStatus(OrderService.CLOSE);
        orderMapper.updateOrderById(order);
        return true;
    }

    @Override
    public List<Map<String, String>> getDistributorOrderList(Map<String, String> map) {
        return orderMapper.getDistributorOrderList(map);
    }
}
